package tech.yunland.shop.web;

import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.domain.model.Organ;
import com.moyuer.bsf.domain.service.OrganService;
import com.moyuer.bsf.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.dao.SNGenerator;
import tech.yunland.shop.domain.model.AllotBill;
import tech.yunland.shop.domain.model.AllotBillEntry;
import tech.yunland.shop.domain.service.AllotBillServiceImpl;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 调拨单控制层
 * Created by v on 17-5-18.
 */
@RestController
@RequestMapping("/allot_bill")
public class AllotBillController extends BaseController {
    @Autowired
    private AllotBillServiceImpl allotBillService;
    @Value("${processdefId}")
    private String processdefId;
    @Autowired
    private SNGenerator snGenerator;
    @Autowired
    private OrganService organService;

    /**
     * 查询所有调拨单
     *
     * @param param
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<Map<String, Object>> getAllPurchaseBill(
            @RequestParam(required = false) String param,
            @RequestParam(required = false) List<Integer> states,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows) {
        Pagination result = new Pagination(page, rows);
        Integer startIdx = result.getStartIdx();
        Integer count = allotBillService.getAllAllotBillSize(param, this.organIds, states);
        List<Map<String, Object>> records = allotBillService.getAllAllotBill(param, this.organIds, states, startIdx, rows);
        result.setCount(count);
        result.setRecords(records);
        return result;
    }

    /**
     * 保存调拨单
     *
     * @param allotBill
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void saveAllotBill(@RequestBody AllotBill allotBill) throws UnsupportedEncodingException {
        // 输出日志
        logger.info(JSON.toJSONString(allotBill, true));

        //判断组织
        if (allotBill.getOrgan() == null) {
            allotBill.setOrgan(primaryOrgan);
        }
        //判断创建人
        if (allotBill.getCreator() == null) {
            allotBill.setCreator(currentUser);
        }
        if (StringUtils.isBlank(allotBill.getInStoreId())) {
            throw new RuntimeException("调入仓库不存在");
        }
        if (StringUtils.isBlank(allotBill.getOutStoreId())) {
            throw new RuntimeException("调出仓库不存在");
        }

        Organ instore = organService.get(allotBill.getInStoreId());
        Organ outstore = organService.get(allotBill.getOutStoreId());
        allotBill.setInStore(instore);
        allotBill.setOutStore(outstore);
        //判断单据数据
        if (allotBill.getEntries() == null || allotBill.getEntries().size() == 0) {
            throw new RuntimeException("商品信息参数错误，没有商品。");
        }


        //保存单据
        allotBillService.saveAllotBill(allotBill);

        saveLog("调拨单：[" + allotBill.getSn() + "] 保存成功！");
    }

    /**
     * 执行调拨单
     *
     * @param id
     */
    @RequestMapping(value = "/allot/{id}", method = RequestMethod.POST)
    public void updateAllotBill(@PathVariable("id") String id) {
        allotBillService.updateAllotBill(id);
    }

    /**
     * 获取调拨单分录集合
     *
     * @param ownerId
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/entry/{ownerId}", method = RequestMethod.GET)
    public Pagination getEntryList(@PathVariable String ownerId,
                                   @RequestParam(required = false) Integer page,
                                   @RequestParam(required = false) Integer rows) {
        Pagination<AllotBillEntry> pagination = new Pagination<AllotBillEntry>(page, rows);
        Integer startIdx = pagination.getStartIdx();
        List<AllotBillEntry> entryList = this.allotBillService.getEntryList(ownerId, startIdx, rows);
        long entryListSize = this.allotBillService.getEntryListSize(ownerId);
        pagination.setCount(((int) entryListSize));
        pagination.setRecords(entryList);
        return pagination;
    }

    /**
     * 获取调拨单分录集合（非分页）
     *
     * @param ownerId
     * @return
     */
    @RequestMapping(value = "/entry/list/{ownerId}", method = RequestMethod.GET)
    public List<AllotBillEntry> getEntryList(@PathVariable String ownerId) {
        return this.allotBillService.getEntryList(ownerId, Integer.valueOf(-1), Integer.valueOf(-1));
    }

    /**
     * 修改调拨单备注
     *
     * @param id
     */
    @RequestMapping(value = "/updateRemark/{id}", method = RequestMethod.POST)
    public void updateRemark(@PathVariable String id,@RequestParam String remark ) {
        this.allotBillService.updateRemark(id,remark);
    }
}
